<?php


namespace App\Services\Common;


use App\Exceptions\ServiceException;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CaptchaService
{
    public function generate(){
        $builder = new CaptchaBuilder();
        $builder->build();
        $key = 'captcha_'.md5(uniqid());
        $code = $builder->getPhrase();
        Cache::put($key, $code, 60); // 2分钟有效期
        return [
            'captcha_key' => $key,
            'code'=>$builder->getPhrase(),
            'captcha_image' => 'data:image/jpeg;base64,' . base64_encode($builder->get())
        ];
    }

    public function verify(Request $request){
        $request->validate([
            'captcha_key' => 'required',
            'captcha_code' => 'required'
        ]);
        $key = $request->captcha_key;
        $correctCode = Cache::get($key);
        if (!$correctCode) {
            throw  new ServiceException('验证码已过期');
        }
        $userInput = $request->captcha_code;
        // 不区分大小写比较
        if (strtolower($userInput) === strtolower($correctCode)) {
            Cache::forget($key);
        }else{
            throw  new ServiceException('验证码错误');
        }
    }
}
